package com.ruoyi.dynamic;

import com.ruoyi.common.annotation.DataSource;
import com.ruoyi.common.config.datasource.DynamicDataSourceContextHolder;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.DataSourceType;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.web.controller.module.mall.good.domain.MallGood;
import com.ruoyi.web.controller.module.mall.good.mapper.MallGoodMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.security.auth.Subject;
import javax.transaction.Transactional;
import java.math.BigDecimal;


/**
 * @Author alison
 * @Date 2024/12/13 22:36
 * @Version 1.0
 * @Description
 */
@Slf4j
@Component
public class DataSourceComponentService {
    @Transactional
    public void testQueryAll() {
        SpringUtils.getAopProxy(this).queryM();
        SpringUtils.getAopProxy(this).querys(); // 在一个类中,无法切换到数据源,最好放在其他类中
//        querys();//无法切换数据源 , 只有通过代理对象才可以走 切面 @Aspect
//        queryM();//无法切换数据源 , 只有通过代理对象才可以走 切面 @Aspect
    }

    @Autowired
    private DsService dsService;
    @Transactional
    public void testDsService() {
        System.out.println("-------2---------");
        System.out.println("Thread.currentThread().getName() = " + Thread.currentThread().getName());
        System.out.println("DynamicDataSourceContextHolder.getDataSourceType() = " + DynamicDataSourceContextHolder.getDataSourceType());
        dsService.querys();
    }

    @Autowired
    private SysUserMapper sysUserMapper;

    @Transactional
    @DataSource(value = DataSourceType.SLAVE)
    public void querys() {
        SysUser user = sysUserMapper.selectUserByLoginName("sched");
        log.info("user: " + user);
    }

//    @Transactional
    @DataSource(value = DataSourceType.MASTER)
    public void queryM() {
        SysUser user = sysUserMapper.selectUserByLoginName("sched");
        log.info("user: " + user);//admin
    }

    @Transactional
    public void testInsert() {
//        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken("admin", "admin123");
//        SecurityUtils.getSubject().runAs(usernamePasswordToken);
        dsService.insertM();
        dsService.insertS();
    }
}
